package com.edais.actions;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.edais.domain.PerMatchCredit;
import com.edais.service.PerMatchService;
import com.edais.util.CommonUtil;
import com.edais.util.Consts;
import com.edais.util.Message;
import com.edais.vo.PerMatchCreditVo;

@Controller
@RequestMapping("/perMatch")

public class PerMatchDetailAction  implements Serializable{
	private static final Log logger = LogFactory.getLog(PerMatchDetailAction.class);

	@Autowired
	private PerMatchService perMatchService;

	/** E500037 获取鼓钱包预匹配标的列表
	 * @param request
	 * @return response
	 * @throws Exception */
	@RequestMapping(value = "/getPerMatchDetailList")
	public void getPerMatchDetailList(HttpServletRequest request, HttpServletResponse response){
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String userId = paramsMap.get("userId");   // 用户id
		String orderId = paramsMap.get("orderId");   // 订单Id
		String preMatchAmount = paramsMap.get("preMatchAmount");   // 签约中金额（9990.00元）预匹配金额
		
		// 用户id为空 或者 订单id为空
		if (StringUtils.isBlank(userId) || StringUtils.isBlank(orderId)) {
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
														Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,
														Message.CnDescriptionExpression.BUSINESSE_ERROR);
			CommonUtil.responseJson(result, response);
			logger.debug("/wallet/getPerMatchDetailList 传入参数为空-----userId or orderId");
			return;
		}

		BigDecimal coreOrderBalance = null;  // 核心取得订单余额
		
		// E300015我的e计划订单详情
		String transCode = "E300015";
		// 设置报文体报文数据
		Map<String, Object> pageModelForWallet = new HashMap<String, Object>();
		pageModelForWallet.put("pageSize", "1");// 每页记录数
		pageModelForWallet.put("nowPage", "1");// 当前页
		pageModelForWallet.put("flag", new ArrayList<Object>());// 交易状态（1.预匹配2.已匹配（还款中）3.回款完成4.流标5.转让中6.已转让）
		pageModelForWallet.put("orderId", orderId);// 订单id

		try {
			// 构建json串
			String jsonStr = CommonUtil.constructJsonStr(transCode, userId, pageModelForWallet);
			// 调用核心接口,获取订单余额
			String rtnStr = CommonUtil.getCoreValue(jsonStr);
			JSONObject jsonObject = JSONObject.fromObject(rtnStr);
			
			// rescode = "00000"
			//boolean flag1 = Consts.SUCCESS_CODE.equals(jsonObject.getString("rescode"));
			//logger.debug(flag1);
			if(Consts.SUCCESS_CODE.equals(jsonObject.getString("rescode"))){
				//boolean flag = jsonObject.containsKey("orderBalance");
				//logger.debug(flag);
				if(jsonObject.containsKey("orderBalance")){
					coreOrderBalance = new BigDecimal(jsonObject.getString("orderBalance"));
				}else{
					coreOrderBalance = new BigDecimal(preMatchAmount);	
				}
			}else{
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
															Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,
															Message.CnDescriptionExpression.BUSINESSE_ERROR);
				CommonUtil.responseJson(result, response);
				logger.debug("/wallet/getPerMatchDetailList 核心取得订单余额异常：");
				logger.debug("核心 " + transCode + " rescode：" + jsonObject.getString("rescode"));
				logger.debug("核心 " + transCode + " resmsg：" + jsonObject.getString("resmsg"));
				return;
			}
		} catch (Exception e) {
			e.printStackTrace();
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
														Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,
														Message.CnDescriptionExpression.BUSINESSE_ERROR);
			CommonUtil.responseJson(result, response);
			logger.debug("/wallet/getPerMatchDetailList 核心取得订单余额异常：" + e.getMessage());
			return;
		}
		
		//预匹配债券列表
		List<PerMatchCredit> perMatchCreditList = new ArrayList<PerMatchCredit>();
		List<PerMatchCreditVo> perMatchCreditVoList = new ArrayList<PerMatchCreditVo>();

		try {
			// 获取预匹配债券列表
			perMatchCreditList = this.perMatchService.getPerMatchCreditList(userId, orderId, coreOrderBalance);
			
		} catch (Exception e) {
			e.printStackTrace();
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
														Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,
														Message.CnDescriptionExpression.BUSINESSE_ERROR);
			CommonUtil.responseJson(result, response);
			logger.debug("/perMatch/getPerMatchDetailList E500037 获取鼓钱包预匹配标的列表：");
			logger.debug(e.getMessage());
			return;	
		}
		//只取5条
		for (PerMatchCredit perMatchCredit : perMatchCreditList) {
			PerMatchCreditVo perMatchCreditVo = new PerMatchCreditVo();
			perMatchCreditVo.setLoanId(String.valueOf(perMatchCredit.getPerMatchCreditId()));   // 标的id
			perMatchCreditVo.setLoanState("招标中"); // 标的状态：招标中
			perMatchCreditVo.setLoanAmount(String.valueOf(perMatchCredit.getContactAmount())); // 借款金额
			perMatchCreditVo.setCreditAmount(String.valueOf(perMatchCredit.getCreditAmount().setScale(2, BigDecimal.ROUND_DOWN)));// 出借金额（9990.00元）
			perMatchCreditVo.setInterest(String.valueOf(perMatchCredit.getInterest()));  // 年化利率（%）
			perMatchCreditVo.setLoanPeriods(String.valueOf(perMatchCredit.getLoanMonths()));   // 贷款期数

			perMatchCreditVoList.add(perMatchCreditVo);
		}
		
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		jsonMap.put("totalNum", String.valueOf(perMatchCreditVoList.size()));
		jsonMap.put("listSize", String.valueOf(perMatchCreditVoList.size()));
		jsonMap.put("list", perMatchCreditVoList);
		
		String result = CommonUtil.setResultStringCn(jsonMap, Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE,"");
		// 处理返回结果
		CommonUtil.responseJson(result, response);
	}
}
